package cn.edu.lingnan.service.impl;

import cn.edu.lingnan.mapper.UserMapper;
import cn.edu.lingnan.service.ExamService;
import cn.edu.lingnan.service.UserService;
import cn.edu.lingnan.user.dtos.*;
import cn.edu.lingnan.user.pojos.PageBean;
import cn.edu.lingnan.user.pojos.User;
import cn.edu.lingnan.user.vos.UserInfoVo;
import cn.edu.lingnan.user.vos.UserVO;
import cn.edu.lingnan.utils.MD5;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.servlet.http.HttpServletResponse;
 import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.security.SecureRandom;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
 public class UserServiceImpl implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ExamService examService;

    @Override
    public PageBean getUserList(UserQueryDTO queryDTO) {
        PageHelper.startPage(queryDTO.getPage(), queryDTO.getSize());
//        //条件查询参数去除空格
        if (queryDTO.getUserName()!= null) {
            queryDTO.setUserName(queryDTO.getUserName().trim());
        }
        if (queryDTO.getNickName()!= null) {
            queryDTO.setNickName(queryDTO.getNickName().trim());
        }
        if (queryDTO.getEmail()!= null) {
            queryDTO.setEmail(queryDTO.getEmail().trim());
        }
       Page<UserVO> users = userMapper.getUserList(queryDTO);

        return new  PageBean(users.getTotal(),users.getResult());
    }

    @Override
    public boolean deleteUserById(Integer userId) {
        //关联考试不能删除
        if (examService.countExamByUserId(userId) > 0) {
            return false;
        }
        //删除用户角色关系表
        userMapper.deleteUserRole(userId);
        //删除用户

        return userMapper.updateUserDelFlag(userId) > 0;
    }

    @Override
    public boolean updateUser(UpdateUserDTO updateUserDTO) {
        return userMapper.updateUser(updateUserDTO) > 0;
    }

    @Override
    public boolean updateStatus(Integer userId, Integer status) {
        return  userMapper.updateStatus(userId, status) > 0;
    }

    @Override
    public void updateUserImage(Long userId, String url) {
        userMapper.updateUserImage(userId, url);
    }

    @Override
    public UserVO getUserById(Integer userId) {
        return  userMapper.getUserById(userId);
    }

    @Override
    public boolean addUser(AddUserDto addUserDto) {
        User user = new User();
        // 对象赋值
        user.setUserName(addUserDto.getUserName().trim());
        user.setNickName(addUserDto.getNickName().trim());
        user.setEmail(addUserDto.getEmail().trim());
        user.setPhoneNumber(addUserDto.getPhoneNumber().trim());
        user.setSex(addUserDto.getSex());
        user.setRemark(addUserDto.getRemark().trim());
        user.setAvatar("https://ongoingife.oss-cn-beijing.aliyuncs.com/user_avatar/default.png");
        user.setType(addUserDto.getType());

        // 设置盐值
        String salt = generateSaltWithAlphanumeric();
        user.setSalt(salt);
        // 设置密码
        user.setUserPassword(MD5.md5Encrypt(addUserDto.getUserPassword().trim() + salt));

        // 插入数据库
        int count = userMapper.insert(user);
        // 此时 user.getUserId() 就能拿到数据库生成的自增id
        System.out.println("新增用户的自增 ID 为：" + user.getUserId());
        //插入用户角色关系表
        userMapper.insertUserRole(user.getUserId(),addUserDto.getType()+1);

        return count > 0;
    }

    @Override
    public void exportUsers(HttpServletResponse response, Integer type, String userName) {
        // 查询数据
        List<User> userRecordVos = userMapper.getUserBytype(type);

        // 创建一个新的工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("用户信息");

        // 创建标题行并居中显示
        Row titleRow = sheet.createRow(0);
        Cell titleCell = titleRow.createCell(0);
        titleCell.setCellValue("用户信息");
        CellStyle titleStyle = createBoldAndCenterCellStyle(workbook);
        titleCell.setCellStyle(titleStyle);
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 10)); // 合并单元格用于标题

        // 创建显示用户名的行
        Row userRow = sheet.createRow(1);
        Cell userCell = userRow.createCell(0);
        userCell.setCellValue("用户: " + userName);
        userCell.setCellStyle(createBoldCellStyle(workbook));
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 10)); // 合并单元格用于用户名

        // 添加导出时间
        Row exportTimeRow = sheet.createRow(2);
        Cell exportTimeCell = exportTimeRow.createCell(0);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        exportTimeCell.setCellValue("导出时间: " + LocalDateTime.now().format(dateTimeFormatter));
        exportTimeCell.setCellStyle(createBoldCellStyle(workbook));
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 10)); // 合并单元格用于导出时间

        // 创建表头行并居中显示
        Row headerRow = sheet.createRow(3);
        String[] headers = {"用户ID", "用户名", "姓名", "邮箱", "手机", "性别", "创建时间", "更新时间", "状态", "角色", "备注"};
        CellStyle headerStyle = createBoldAndCenterCellStyle(workbook);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(headerStyle);
        }

        // 填充数据行并居中显示
        CellStyle contentStyle = createCenterCellStyle(workbook);
        int rowIndex = 4;
        for (User user : userRecordVos) {
            Row row = sheet.createRow(rowIndex++);
            row.createCell(0).setCellValue(user.getUserId());
            row.createCell(1).setCellValue(user.getUserName());
            row.createCell(2).setCellValue(user.getNickName());
            row.createCell(3).setCellValue(user.getEmail());
            row.createCell(4).setCellValue(user.getPhoneNumber());
            row.createCell(5).setCellValue(user.getSex() == 1 ? "男" : "女");
            row.createCell(6).setCellValue(user.getCreateTime().format(dateTimeFormatter));
            row.createCell(7).setCellValue(user.getUpdateTime().format(dateTimeFormatter));
            row.createCell(8).setCellValue(user.getStatus() == 1 ? "正常" : "冻结");

            // 角色判断
            if (user.getType() == 0) {
                row.createCell(9).setCellValue("管理员");
            } else if (user.getType() == 1) {
                row.createCell(9).setCellValue("教师");
            } else {
                row.createCell(9).setCellValue("学生");
            }

            row.createCell(10).setCellValue(user.getRemark());

            // 为每个单元格设置居中样式
            for (int i = 0; i <= 10; i++) {
                row.getCell(i).setCellStyle(contentStyle);
            }
        }

        // 设置响应类型以便下载
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=users.xlsx");

        // 使用 try-catch 处理 IO 异常
        try {
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("导出数据时发生 IO 错误", e);
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public UserInfoVo getPasswordByUserId(String userId) {
        return userMapper.getPasswordByUserId(userId);
    }

    @Override
    public boolean updatePassword(UpdatePasswordDto updatePasswordDto) {
        UserInfoVo userInfoVo = userMapper.getPasswordByUserId(updatePasswordDto.getUserId());
        if (userInfoVo == null) {
            return false;
        }

        String oldPasswordHash = MD5.md5Encrypt(updatePasswordDto.getOldPassword() + userInfoVo.getSalt());
        if (!oldPasswordHash.equals(userInfoVo.getUserPassword())) {
            return false;
        }

        String newPasswordHash = MD5.md5Encrypt(updatePasswordDto.getNewPassword() + userInfoVo.getSalt());
        int rowsAffected = userMapper.updatePassword(updatePasswordDto.getUserId(), newPasswordHash);
        return rowsAffected > 0;
    }

    @Override
    public Result forgetPassword(ForgetPwdDto forgetPwdDto) {
        if(forgetPwdDto== null){
            return Result.error("参数错误");
        }
        //先判断对应邮箱用户是否存在
        UserInfoVo userInfoVo = userMapper.getUserByEmail(forgetPwdDto.getEmail());
        if(userInfoVo==null){
            return Result.error("用户不存在");
        }
        //根据用户pwd+salt加密
        String salt =userInfoVo.getSalt();
        System.out.println("salt:"+salt);
        System.out.println("密码"+forgetPwdDto.getNewPassword());
        String newPasswordHash = MD5.md5Encrypt(forgetPwdDto.getNewPassword() + salt);
        System.out.println();
        System.out.println("newPasswordHash:"+newPasswordHash);
        forgetPwdDto.setNewPassword(newPasswordHash);
        if(userMapper.updatePassword(userInfoVo.getUserId(),forgetPwdDto.getNewPassword())>0){
            return Result.success();
        }


        return  Result.error("修改失败");
    }


    // 创建加粗并居中样式的方法
    private CellStyle createBoldAndCenterCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);
        return style;
    }

    // 创建加粗样式的方法
    private CellStyle createBoldCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);
        return style;
    }

    // 创建居中样式的方法
    private CellStyle createCenterCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        return style;
    }


    /**
     * 生成随机六位由字母和数字组合的盐值
     */
    private String generateSaltWithAlphanumeric() {
        SecureRandom random = new SecureRandom();
        StringBuilder salt = new StringBuilder();
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        for (int i = 0; i < 6; i++) {
            int index = random.nextInt(chars.length());
            salt.append(chars.charAt(index));
        }
        return salt.toString();
    }
}
